import axios from 'axios';

const service = axios.create({
  baseURL: 'https:/v3pz.itndedu.com/v3pz',
  timeout: 10000,
});

//request interceptor 请求拦截
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('pz_token');
    console.log('token', token);
    const whiteUrl = ['/get/code', '/user/authentication', '/login'];
    if (token && !whiteUrl.includes(config.url)) {
      // 有俩种方案:1.是登录时开始计时,到时间重新登录,2.是一发送请求就重新存入时间戳,重新计时
      // const loginTime = localStorage.getItem('loginTime')
      // const outTime = 7200000
      // if (Date.now() - loginTime > outTime) {
      //   store.dispatch('user/logout')
      //   router.push('/login')
      //   return Promise.reject(new Error('token已过期'))
      // }
      config.headers['x-token'] = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// response interceptor 响应拦截
service.interceptors.response.use(
  (res) => {
    //   对接口异常的数据给用户提示
    if (res.data.code === -1) {
      ElMessage.warning(res.data.msg);
    }
    console.log(res.data);

    // token过期或者出错
    if (res.data.code === -2) {
      localStorage.removeItem('pz_token');
      localStorage.removeItem('pz_userInfo');
      // 跳转为原始路径
      window.location.href = window.location.origin;
    }
    return res;
  },
  (err) => {
    // 超出2xx的范围的状态码都会触发该函数
    return Promise.reject(err);
  }
);

export default service;
